package com.xx.sg.controller;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.xx.sg.own.entity.CommunicationDevice;
import com.xx.sg.own.service.CommunicationDeviceService;
import com.xx.sg.ws.MyWebSocketHandler;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/stream")
@Tag(name = "流媒体服务Api", description = "流媒体服务Api")
public class StreamController {

    @Autowired
    private CommunicationDeviceService communicationDeviceService;

    @PostMapping("/on_publish")
    public String onPublish(HttpServletRequest request) {
        String name = request.getParameter("name");
        String app = request.getParameter("app");
        String addr = request.getRemoteAddr();

        LambdaUpdateWrapper<CommunicationDevice> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(CommunicationDevice::getName, name)
                .set(CommunicationDevice::getPlayStatus, true);
        communicationDeviceService.update(wrapper);

        MyWebSocketHandler.broadcast("new_video_publish");
        System.out.println("推流开始: " + name + ", 应用: " + app + ", 来自: " + addr);
        return "OK"; // 返回 "OK" 表示允许推流
    }

    @PostMapping("/on_publish_done")
    public String onPublishDone(HttpServletRequest request) {
        String name = request.getParameter("name");
        LambdaUpdateWrapper<CommunicationDevice> wrapper = new LambdaUpdateWrapper<>();
        wrapper.eq(CommunicationDevice::getName, name)
                .set(CommunicationDevice::getPlayStatus, false);
        communicationDeviceService.update(wrapper);
        MyWebSocketHandler.broadcast("video_publish_done");
        System.out.println("推流结束: " + name);
        return "OK";
    }
}
